package tech.xiaozai.rbac.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.xiaozai.common.CommonPage;
import tech.xiaozai.rbac.mapper.SysRoleMapper;
import tech.xiaozai.rbac.po.SysRole;
import tech.xiaozai.rbac.po.SysRoleExample;

import java.util.List;

/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-09-17 08:46
 */

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private SysRoleMapper roleMapper;


    @Override
    public SysRole getById(Long id){
        SysRole sysRole = roleMapper.selectByPrimaryKey(id);
        return sysRole;
    }


    @Override
    public CommonPage<SysRole> page(Integer pageNum, Integer pageSize, SysRole role){
        PageHelper.startPage(pageNum,pageSize);
        SysRoleExample example =null;
        if(role!=null) {

            if (role.getName() != null && !role.getName().trim().isEmpty()) {
                example = new SysRoleExample();
                example.createCriteria().andNameLike("%" + role.getName() + "%");
            }
        }
        Page<SysRole> page = (Page<SysRole>) roleMapper.selectByExample(example);
        return new CommonPage<SysRole>().setPageNum(page.getPageNum())
                .setPageSize(page.getPageSize())
                .setTotal(page.getTotal())
                .setTotalPages(page.getPages())
                .setList(page.getResult());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(SysRole role){
        roleMapper.insertSelective(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysRole role){
        roleMapper.updateByPrimaryKeySelective(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id){
        roleMapper.deleteByPrimaryKey(id);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids){
        SysRoleExample example = new SysRoleExample();
        example.createCriteria().andIdIn(ids);
        roleMapper.deleteByExample(example);
    }

    @Override
    public List<SysRole> all() {

        return roleMapper.selectByExample(null);
    }

}
